  /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Employee;

import Address.AddressBean;
import SalaryComponent.EmpSalDetailsBean;
import SalaryComponent.EmpSalaryBean;
import User.UserBean;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Mukesh
 */
public class EmployeeRegistration extends HttpServlet {

    HashMap htmlfields = new HashMap();
    UserBean ub = new UserBean();
    AddressBean adb = new AddressBean();
    EmployeeBean eb = new EmployeeBean();
    int i = 0;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Date doj = null;
        HttpSession session = request.getSession();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            try {
                ServletFileUpload servlet = new ServletFileUpload();
                FileItemIterator fit = servlet.getItemIterator(request);
                while (fit.hasNext()) {
                    FileItemStream f = fit.next();
                    if (f.isFormField()) {
                        InputStream input = f.openStream();
                        byte b[] = new byte[input.available()];
                        input.read(b);
                        String value = new String(b);
                        htmlfields.put(f.getFieldName(), value);
                    } else {
                        if (f.getName().isEmpty()) {
                            continue;
                        } else {
                            String fileName = (String) htmlfields.get("email");
                            String postfix = "@photo";

                            String s = DocUpload.FileUpload.writeFile(f, fileName + postfix);
                            eb.setPhoto(s);
                        }
                    }
                }
            } catch (FileUploadException e) {
                session.setAttribute("msg", "Check file & Try Again...! Not Done.(" + e + ")");
                session.setAttribute("status", "fail");
                getServletContext().getRequestDispatcher("/Services/HR/AddEmployee.jsp").forward(request, response);
            } catch (IOException e) {
                session.setAttribute("msg", "Try Again...! Not Done.(" + e + ")");
                session.setAttribute("status", "fail");
                getServletContext().getRequestDispatcher("/Services/HR/AddEmployee.jsp").forward(request, response);
            }
        }
        try {
////--------------------Loging Details part -------------------------
            ub.setEmployeeName(htmlfields.get("empName").toString());
            String td[] = htmlfields.get("empDob").toString().split("/");
            if (td.length == 3) {
                ub.setDob(new Date(Integer.parseInt(td[2]) - 1900, Integer.parseInt(td[0]) - 1, Integer.parseInt(td[1])));
            } else {
                ub.setDob(null);
            }
            ub.setEmail(htmlfields.get("email").toString());
            ub.setPassword(htmlfields.get("pwd").toString());
            ub.setUserType(htmlfields.get("eType").toString());
            ub.setUserStatus(0);
            ub.setEntryEmail(session.getAttribute("uid").toString());
            i = User.Query.add(ub);
////--------------------Loging Details part end-------------------------
            if (i != 0) {
// -------------------------------------Empoyee Personal Deails End----------------------------
                adb.setAddress1(htmlfields.get("add1").toString());
                adb.setAddress2(htmlfields.get("add2").toString());
                if (htmlfields.get("country").toString().length() != 0) {
                    adb.setCountryId(Integer.parseInt(htmlfields.get("country").toString()));
                }
                if (htmlfields.get("state").toString().length() != 0) {
                    adb.setStateId(Integer.parseInt(htmlfields.get("state").toString()));
                }
                adb.setPinCode(htmlfields.get("pin").toString());
                eb.setAddressId(Address.Query.add(adb));

                eb.setUserId(i);
                if (!htmlfields.get("doj").equals("")) {
                    SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy");
                    java.util.Date d = (java.util.Date) formatter1.parse(htmlfields.get("doj").toString());
                    doj = new Date(d.getTime());
                }
                eb.setDoj(doj);
                eb.setEmployeeFatherName(htmlfields.get("fname").toString());
                eb.setPanCard(htmlfields.get("pcard").toString());
                eb.setMobile(htmlfields.get("mno").toString());
                eb.setPhone(htmlfields.get("pno").toString());
                eb.setGender(htmlfields.get("gender").toString());
                eb.setHigherQuali(htmlfields.get("hquali").toString());
                eb.setJobdetails(htmlfields.get("jdetail").toString());
                if (htmlfields.get("department").toString().length() != 0) {
                    eb.setDepartmentId(Integer.parseInt(htmlfields.get("department").toString()));
                }
                if (htmlfields.get("designation").toString().length() != 0) {
                    eb.setDesignationId(Integer.parseInt(htmlfields.get("designation").toString()));
                }
                if (htmlfields.get("empType").toString().length() != 0) {
                    eb.setEmployeeType(Integer.parseInt(htmlfields.get("empType").toString()));
                }
                if (htmlfields.get("empStatus").toString().length() != 0) {
                    eb.setEmployeeStatus(Integer.parseInt(htmlfields.get("empStatus").toString()));
                }

                int l = Employee.Query.add(eb);
// ----------------------------------Empoyee Personal Deails End-----------------------------------
                if (i != 0) {

                  /*  SalaryComponent.EmpSalaryBean empBean = new EmpSalaryBean();
                    if (htmlfields.get("tote").toString().length() != 0) {
                        empBean.setTotalEarning(Float.parseFloat(htmlfields.get("tote").toString()));
                    }
                    if (htmlfields.get("tota").toString().length() != 0) {
                        empBean.setTotalSal(Float.parseFloat(htmlfields.get("tota").toString()));
                    }
                    if (htmlfields.get("totd").toString().length() != 0) {
                        empBean.setTotalDeduction(Float.parseFloat(htmlfields.get("totd").toString()));
                    }
                    empBean.setUserId(i);
                    //empBean.setUserId(1);
                    int empSal = SalaryComponent.Query.addEmpSal(empBean);
//-----------------------------------------------------------------
                    if (empSal != 0) {
                        Vector<Object> list = new Vector<Object>();
                        String[] token = htmlfields.get("noc").toString().split("-");
                        for (int k = 0; k < token.length - 1; k++) {
                            if (token[k].length() != 0) {
                                String[] compId = token[k].split("/");
                                EmpSalDetailsBean esdb = new EmpSalDetailsBean();
                                esdb.setEmpSalId(empSal);
                                esdb.setSalCompoId(Integer.parseInt(compId[0]));
                                esdb.setAmount(Float.parseFloat(htmlfields.get("tota").toString()));
                                list.add(esdb);
                            }
                        }
                        int salDetail = SalaryComponent.Query.addEmpSalDetails(list);
                        if (salDetail != 0) {*/
                            session.setAttribute("msg", "Employee "+htmlfields.get("empName").toString()+" Created Successfully.");
                            session.setAttribute("status", "success");
                            getServletContext().getRequestDispatcher("/Services/HR/AddEmployee.jsp").forward(request, response);
//                        }
//                    }
                } else {
                    session.setAttribute("msg", "Check Personal Details and Try Again...!");
                    session.setAttribute("status", "fail");
                    getServletContext().getRequestDispatcher("/Services/HR/AddEmployee.jsp").forward(request, response);
                }
            } else {
                session.setAttribute("msg", "Check Login Details and Try Again...!");
                session.setAttribute("status", "fail");
                getServletContext().getRequestDispatcher("/Services/HR/AddEmployee.jsp").forward(request, response);
            }

        } catch (Exception e) {
            session.setAttribute("msg", "Try Again...! Not Done.(e)");
            session.setAttribute("status", "fail");
            getServletContext().getRequestDispatcher("/Services/HR/AddEmployee.jsp").forward(request, response);
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(EmployeeRegistration.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(EmployeeRegistration.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
